import axios from 'axios'
import type { AxiosRequestHeaders } from 'axios'
import router from '@/router'

import { ElLoading, ElMessage } from 'element-plus'

axios.defaults.baseURL = 'http://localhost:5000'

let loadingInstance: any = null
axios.interceptors.request.use((config) => {
  loadingInstance = ElLoading.service({ fullscreen: true })
  if (localStorage.getItem('token')) {
    (config.headers as AxiosRequestHeaders).Authorization = localStorage.token
  }
  return config
}, err => {
  return Promise.reject(err)
})
axios.interceptors.response.use(response => {
    loadingInstance.close()
    return response
},err => {
  loadingInstance.close()
  ElMessage.error(err.response.data)
  const {status} = err.response
  if(status == 401){
    ElMessage.error('token失效,请重新登录！')
    localStorage.removeItem('token')
    router.push('/login')
  }
  return Promise.reject(err)
})

export default axios